package com.cy.embeddingdemo.testAgent;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.cy.embeddingdemo.config.MinioConfig;
import com.cy.embeddingdemo.service.TaskManagerService;
import com.cy.embeddingdemo.util.MinerUutil;
import com.cy.embeddingdemo.util.MinioUtils;
import com.cy.embeddingdemo.util.RedisUtil;
import com.cy.embeddingdemo.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@RequestMapping("mineru")
@RestController
public class MineruController {

    @Resource
    private TaskManagerService taskManagerService;

    @Resource
    private MinioUtils minioUtils;

    @Resource
    private MinioConfig minioConfig;


    private static String CREATE_TASK_URL = "https://mineru.net/api/v4/extract/task";
    private static String CHECK_TASK_URL = "https://mineru.net/api/v4/extract/task/";

    private static String AUTHORIZATION_TOKEN = "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiI4MjYwMDQ4OSIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc0MzMwMTgzOCwiY2xpZW50SWQiOiJsa3pkeDU3bnZ5MjJqa3BxOXgydyIsInBob25lIjoiIiwib3BlbklkIjpudWxsLCJ1dWlkIjoiMmRkYWY2YmUtM2Q3ZC00MDA1LTg3MjQtZTA4YmNjYTBiNjk0IiwiZW1haWwiOiIiLCJleHAiOjE3NDQ1MTE0Mzh9.0l7hUfXDCcc-SDBi5LNXHqTAa7auIvX-nlv0qQuM20DlSd3PnG9wVHV2SmB9763IQjFeYvLafj61BAl7ngA2hQ";


    @RequestMapping("upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file, String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            fileName = file.getOriginalFilename();
        }

        minioUtils.upload(file,fileName);  //上传的存储桶是 public，可以直接拼接出文件路径
         String fileUrl = minioConfig.getUrl() + "/"+minioConfig.getBucketName()+"/" + fileName;
//        String fileUrl =   "http://1.15.135.14:9000/" +minioConfig.getBucketName()+"/" + fileName;
        taskManagerService.crateMinerUTask(fileUrl);  //提交pdf 解析任务

        return Result.success("上传成功");
    }

    @GetMapping("ddd")
    public void ddd() {

        try {
            taskManagerService.processPDFContent("f7acd625-0850-4579-9460-d695bb5cadd1");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }


    public static void main(String[] args) {

        // 设置任务 ID 和 URL
        String taskId = "6b42ea24-8c8a-4c52-b66a-b07db2ebac1e"; // 替换为实际的任务 ID
        String url = "https://mineru.net/api/v4/extract/task/" + taskId;

        // 设置请求头
         HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .header("Authorization", AUTHORIZATION_TOKEN)
                .GET()
                .build();

        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newHttpClient();

        try {
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 打印响应状态码
            System.out.println("Status Code: " + response.statusCode());

            // 打印响应头
            HttpHeaders headers = response.headers();
            headers.map().forEach((k, v) -> System.out.println(k + ":" + v));

            // 打印响应体
            System.out.println("Response Body: " + response.body());

            // 解析响应体中的 "data" 字段


            // 解析响应体中的 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> responseBody = objectMapper.readValue(response.body(), Map.class);

            String state = (String) ((Map<String, Object>) responseBody.get("data")).get("state");

            // 检查 state 是否为 done
            if ("done".equals(state)) {
                // 获取 full_zip_url
                String fullZipUrl = (String) ((Map<String, Object>) responseBody.get("data")).get("full_zip_url");
                System.out.println("Full ZIP URL: " + fullZipUrl);


                String tempFileName = fullZipUrl.substring(fullZipUrl.lastIndexOf("/") + 1);
                // 下载文件
                MinerUutil.downloadFile(fullZipUrl, tempFileName);

                // 解压文件
                MinerUutil.unzipFile(tempFileName, "unzipped_files/"+tempFileName.replace(".zip",""));

                // 删除文件
                MinerUutil.deleteFile(tempFileName);




            } else {
                System.out.println("Task is not done yet.");
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

    }

}
